package com.ftp;

	import java.io.File;
	import java.io.FileOutputStream;
	import java.io.IOException;
	import java.text.SimpleDateFormat;
	import java.util.ArrayList;
	import java.util.Date;
	import java.util.List;
	 
	import org.apache.commons.net.ftp.FTPClient;
	import org.apache.commons.net.ftp.FTPClientConfig;
	import org.apache.commons.net.ftp.FTPFile;
	import org.apache.commons.net.ftp.FTPReply;

import DemoTest.util.FtpParamConfig;
	 
	/*******************************************************************************
	 * 功能说明: 从ftp服务器指定目录复制文件到本地指定路径
	 * 
	 ******************************************************************************/
	public class FtpDownFiles {
	 
		private FTPClient ftpClient;
	 
		public FtpDownFiles() {
			this.ftpClient = new FTPClient();
		}
	 
		/**
		 * 功能说明：通过递归实现ftp目录文件与本地文件同步更新,返回1-成功或未执行操作；0-失败
		 * 
		 * @param ftpfilepath
		 *            当前ftp目录
		 * @param localpath
		 *            当前本地目录
		 * @throws Exception 
		 */
	 
		public void ftpDownFiles(String ftpfilepath, String localpath, List list) throws Exception {
			
			if (!localpath.endsWith("/")) {
				localpath = localpath + "/";
			}
			
			FTPFile[] ff = ftpClient.listFiles(ftpfilepath);
			int fflength = ff.length;
			if (null != ff && fflength > 0) {
				for (int i = 0; i < fflength; i++) {
					String localfilepath = localpath + ff[i].getName();
					File localFile = new File(localfilepath);
					Date fflastModifiedDate = ff[i].getTimestamp().getTime();
					Date localLastModifiedDate = new Date(localFile
							.lastModified());
					int result = localLastModifiedDate
							.compareTo(fflastModifiedDate);
					if (ff[i].isDirectory()) {
						localFile.mkdir();
						String ftpfp = ftpfilepath + ff[i].getName() + "/";
						String localfp = localfilepath + "/";
						this.ftpDownFiles(ftpfp, localfp, list);
	 
					} else if (ff[i].isFile()) {
						if (ff[i].getSize() != localFile.length() || result < 0) {
							String filepath = ftpfilepath + ff[i].getName();
							FileOutputStream fos = new FileOutputStream(localFile);
							
							filepath = new String(filepath.getBytes("GBK"),"ISO-8859-1");
							System.out.println(filepath);
							
							//测试异常使用
							//disConnectServer();
							
							boolean boo = ftpClient.retrieveFile(filepath, fos);
							if (localFile.getPath() != null) {
								if (localFile.getPath().indexOf("xml") > -1) {
									String aaa = localFile
											.getPath()
											.substring(
													localFile.getPath()
															.indexOf("xml") - 1,
													localFile.getPath()
															.length());
									if (aaa.equals(".xml")) {
										list.add(localFile.getPath());
									}
									System.out.println();
								}
							}
	 
							if (boo == true) {
								String name = ff[i].getName();
								String dir = localpath;
								SimpleDateFormat sdf = new SimpleDateFormat(
										"yyyy-MM-dd HH:mm:ss");
								String time = sdf.format(localFile
										.lastModified());
							} 
							
							fos.flush();
							fos.close();
						} else {
							
						}
					}
				}
			} else {
				
			}
					
		}
	 
		public void connectServer(String hostip, String username, String password,
				int port) {
			try {
				FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
				conf.setServerLanguageCode("zh");
				ftpClient.configure(conf); 
				ftpClient.connect(hostip, port);
				ftpClient.login(username, password);
				int reply = ftpClient.getReplyCode();
				if (!FTPReply.isPositiveCompletion(reply)) {
					ftpClient.disconnect();
				}
				
				ftpClient.setControlEncoding("GBK");
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
	 
			} catch (Exception e) {
				e.printStackTrace();
	 
			}
		}
		
		public void ftpChangeWorkDirDownFiles(String ftpfilepath, String localpath, List list) throws Exception {
			
			System.out.println("Now WorkingDirectory is:" + ftpClient.printWorkingDirectory());
			
			if (!localpath.endsWith("/")) {
				localpath = localpath + "/";
			}
	 
			boolean res = ftpClient.changeWorkingDirectory(ftpfilepath);
			System.out.println("Now WorkingDirectory is:" + ftpClient.printWorkingDirectory());
			
			FTPFile[] ff = null;
			if(res) {
				ff = ftpClient.listFiles();			
			} else {
				return;
			}
		
			int fflength = ff.length;
			if (null != ff && fflength > 0) {
				for (int i = 0; i < fflength; i++) {
					String localfilepath = localpath + ff[i].getName();
					File localFile = new File(localfilepath);
					Date fflastModifiedDate = ff[i].getTimestamp().getTime();
					Date localLastModifiedDate = new Date(localFile
							.lastModified());
					int result = localLastModifiedDate
							.compareTo(fflastModifiedDate);
					if (ff[i].isDirectory()) {
						localFile.mkdir();
						String ftpfp = ff[i].getName();
						String localfp = localfilepath + "/";
						this.ftpChangeWorkDirDownFiles(ftpfp, localfp, list);
	 
					} else if (ff[i].isFile()) {
						if (ff[i].getSize() != localFile.length() || result < 0) {
							//String filepath = ftpfilepath + ff[i].getName();
							String filepath = ff[i].getName();
							FileOutputStream fos = new FileOutputStream(localFile);
							
							filepath = new String(filepath.getBytes("GBK"),"ISO-8859-1");
							System.out.println(filepath);
							
							//测试异常使用
							//disConnectServer();
							
							boolean boo = ftpClient.retrieveFile(filepath, fos);
							
							if (localFile.getPath() != null) {
								if (localFile.getPath().indexOf("xml") > -1) {
									String aaa = localFile
											.getPath()
											.substring(
													localFile.getPath()
															.indexOf("xml") - 1,
													localFile.getPath()
															.length());
									if (aaa.equals(".xml")) {
										list.add(localFile.getPath());
									}
									System.out.println();
								}
							}
	 
							if (boo == true) {
								String name = ff[i].getName();
								String dir = localpath;
								SimpleDateFormat sdf = new SimpleDateFormat(
										"yyyy-MM-dd HH:mm:ss");
								String time = sdf.format(localFile
										.lastModified());
							} 
							
							fos.flush();
							fos.close();
						} else {
							
						}
					}
				}
			} else {
				
			}		
		}			
		
		public void disConnectServer(){
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		public static void main(String[] args) {
			FtpDownFiles fd = new FtpDownFiles();
	//		fd.connectServer(FtpParamConfig.getInstance().getFtpHost(), FtpParamConfig.getInstance().getUserName(), FtpParamConfig.getInstance().getPassword(),FtpParamConfig.getInstance().getFtpPort());
			fd.connectServer("39.96.33.164", "ejiao", "123456",21);
			List list = new ArrayList();
			//String importpath ="/"+ DateUtil.formatDate2Str(DateUtil.getNextDay(new Date()),"yyyyMMdd")+"/";
			String importpath ="/opt/server/images/";
			//String importpath =DateUtil.formatDate2Str(DateUtil.getNextDay(new Date()),"yyyyMMdd");
			try {
				//fd.ftpDownFiles(importpath,"d:/aaa/",list);
				fd.ftpChangeWorkDirDownFiles(importpath,"d://",list);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

